/**
 * Copyright (c) 2009 eXtensible Catalog Organization
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the MIT/X11 license. The text of the
 * license can be found at http://www.opensource.org/licenses/mit-license.php and copy of the license can be found on the project
 * website http://www.extensiblecatalog.org/.
 *
 */

package xc.mst.action.repository;

import org.apache.log4j.Logger;

import xc.mst.action.BaseActionSupport;
import xc.mst.bo.provider.Provider;
import xc.mst.constants.Constants;
import xc.mst.dao.DatabaseConfigException;

/**
 * This class is used to delete a repository from the database
 * 
 * @author Tejaswi Haramurali
 */
public class DeleteRepository extends BaseActionSupport {

    /** Generated by eclipse */
    private static final long serialVersionUID = 4498437059514909755L;

    /** A reference to the logger for this class */
    static Logger log = Logger.getLogger(Constants.LOGGER_GENERAL);

    /** The ID of the repository to be deleted */
    private int repositoryId;

    /** Error type */
    private String errorType;

    /** Message explaining why the repository cannot be deleted */
    private String message;

    /** Determines whether repository is deleted */
    private boolean deleted;

    /**
     * Overrides default implementation to delete a repository.
     * 
     * @return {@link #SUCCESS}
     */
    @Override
    public String execute() {
        try {
            log.debug("******* DeleteRepository in execute()!");
            log.debug("DeleteRepository:execute():Repository Id whose records shall be marked deleted : " + repositoryId);

            Provider provider = getProviderService().getProviderById(repositoryId);

            if (provider == null) {
                this.addFieldError("viewRepositoryError", "Error occurred while deleting repository. An email has been sent to the administrator");
                getUserService().sendEmailErrorReport();
                errorType = "error";
                return SUCCESS;
            }

            // Delete provider only if it is not harvested.
            if (provider.getLastHarvestEndTime() != null) {
                message = "Repository has harvested data.";
                deleted = false; // this flag will be used by the jsp page to decide whether to show the 2nd dialog.
            } else {
                markRecordsForDeletion(provider);
                deleted = true;
            }
            return SUCCESS;

        } catch (DatabaseConfigException dce) {
            log.error(dce.getMessage(), dce);
            errorType = "error";
            this.addFieldError("dbConfigError", "Unable to access the database. There may be a problem with database configuration.");
            return INPUT;
        }
    }

    /**
     * Delete repository and its harvested records
     * This is called after the user says yes to the 2nd dialog, knowing that there are harvested records.
     * 
     */
    public String deleteRepositoryAndRecords() {
        try {
            log.debug("DeleteRepository:deleteRepositoryAndRecords():Repository Id to be deleted : " + repositoryId);
            Provider provider = getProviderService().getProviderById(repositoryId);

            markRecordsForDeletion(provider);
            return SUCCESS;
        } catch (Exception e) {
            log.debug("", e);
            this.addFieldError("viewRepositoryError", "Repository cannot be marked deleted");
            errorType = "error";
            return INPUT;
        }
    }

    /**
     *
     */
    private String markRecordsForDeletion(Provider provider) {
        if (log.isDebugEnabled()) {
            log.debug("DeleteRepository:markRecordsForDeletion()");
        }

        // schedule it
        getProviderService().markProviderDeleted(provider);

        return SUCCESS;
    }

    /**
     * Returns error type
     * 
     * @return error type
     */
    public String getErrorType() {
        return errorType;
    }

    /**
     * Sets error type
     * 
     * @param errorType
     *            error type
     */
    public void setErrorType(String errorType) {
        this.errorType = errorType;
    }

    /**
     * Returns the error message
     * 
     * @return error message
     */
    public String getMessage() {
        return message;
    }

    /**
     * Returns true if repository deleted, else false
     * 
     * @return Returns true if repository deleted, else false (for JSON object)
     */
    public boolean isDeleted() {
        return deleted;
    }

    /**
     * Set the ID of the repository to be deleted
     * 
     * @param repositoryId
     *            The ID of the repository to be deleted
     */
    public void setRepositoryId(int repositoryId) {
        this.repositoryId = repositoryId;
    }

    /**
     * Gets the ID of the repository to be deleted
     * 
     * @return The ID of the repository to be deleted
     */
    public int getRepositoryId() {
        return repositoryId;
    }

}
